package cn.layou.dp;

import java.util.LinkedList;
import java.util.List;

/**
 * 责任链模式
 *
 * @author layou
 * @date 2021-04-23
 **/
public class T01_ChainOfResponsibility {
    public static void main(String[] args) {
        Request request = new Request();
        Response response = new Response();
        HtmlFilter htmlFilter = new HtmlFilter();
        JsonFilter jsonFilter = new JsonFilter();
        FilterChain chain = new FilterChain();
        chain.filters.add(htmlFilter);
        chain.filters.add(jsonFilter);
        chain.doFilter(request, response);
        System.out.println(request.str);
        System.out.println(response.str);
    }
}

class Request {
    String str = "";
}

class Response {
    String str = "";
}

interface Filter {
    void doFilter(Request request, Response response, FilterChain chain);
}

class FilterChain {
    List<Filter> filters = new LinkedList<>();
    private int index = 0;

    public void doFilter(Request request, Response response) {
        if(index == filters.size()) {
            return;
        }
        Filter filter = filters.get(index);
        index ++;
        filter.doFilter(request, response, this);
    }
}

class HtmlFilter implements Filter {

    @Override
    public void doFilter(Request request, Response response, FilterChain chain) {
        request.str += " html request";
        chain.doFilter(request, response);
        response.str += " html response";
    }
}

class JsonFilter implements Filter {

    @Override
    public void doFilter(Request request, Response response, FilterChain chain) {
        request.str += " json request";
        chain.doFilter(request, response);
        response.str += " json response";
    }
}